package com.runner.player.state;

import com.badlogic.gdx.math.MathUtils;
import com.runner.entity.CollisionEntity;
import com.runner.player.Player;
import com.runner.utility.Locator;

public class FallingState extends PlayerState {

	private boolean hitGround;
	private boolean requestRoll;
	private float angle;
	private float startAngle;
	private float endAngle;
	private float timer;
	private float spinTimer, spinTime;
	private float height;
	private float targetHeight;
	private float spinAngle;

	public FallingState(Player p) {
		super(p);
	}

	@Override
	public void update(float delta) {
		timer += delta;
		spinTimer+=delta;
		if (timer <= 0.4f) {
			angle = startAngle - (timer / 0.4f * (startAngle - endAngle));
			player.getPhysics().getBody().setTransform(player.getPhysics().getBody().getPosition(), angle);
		}
		if (spinTimer <= spinTime) {
			spinAngle = startAngle - (spinTimer/spinTime * (startAngle - -2*MathUtils.PI));
			player.setDirection(spinAngle * MathUtils.radiansToDegrees);
		}
		if (hitGround) {
			exit();
		}
	}

	@Override
	public void newAction(INPUT input) {
		switch (input) {
		case ROLL:
			requestRoll = true;
			break;
		default:
			break;

		}
	}

	@Override
	public void enter() {
		requestRoll = false;
		timer = 0;
		spinTimer=0;
		hitGround = false;
		targetHeight = GROUND_HEIGHT * Locator.getySpriteScale();
		height = player.getPhysics().getBody().getPosition().y;
		startAngle = player.getPhysics().getBody().getAngle();
		spinAngle = startAngle;
		spinTime = (height - targetHeight) / 5;
		endAngle = -MathUtils.PI;
		player.getPhysics().getBody().setGravityScale(2);
	}

	@Override
	public void exit() {
		player.getPhysics().getBody().setTransform(player.getPhysics().getBody().getPosition(), 0);
		player.setDirection(0);
		if (requestRoll) {
			player.changeState(new RollState(player));
		} else {
			player.changeState(new NormalState(player));
		}
	}

	@Override
	public void collide(CollisionEntity otherBody) {
		if (otherBody.getPhysics().getType().equals(TYPE.GROUND)) {
			hitGround = true;
		}
	}

}
